import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
//添加路由守卫
router.beforeEach(async (to, from, next) => {
  // 启动用一个进度条
  NProgress.start()
  // 更改页面的浏览器的title
  document.title = getPageTitle(to.meta.title)
  //获取token
  const hasToken = getToken()
  if (hasToken) {
    //如果来就用户请求的就是登陆页面，就直接放行
    if (to.path === '/login') {
      next({path: '/'})
      //关闭进度条
      NProgress.done()
    } else {
      //判断用户是否权限
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        //如果有权限就直接放行
        next()
      } else {
        try {
          //重新拉取权限
          const {permissions} = await store.dispatch('user/getInfo')
          //获取菜单
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          // 添加动态菜单
          router.addRoutes(accessRoutes)
          //路由跳转
          next({...to, replace: true})
        } catch (error) {
          //如果出异常就回到登陆页面
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    //判断是否是白名单
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      //不在白名称就回到登陆页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
